using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using SeguradoraIA.Framework.Data;

namespace SeguradoraIA.Framework.Log.DefaultLoggers
{
    public class SqlLogger : ILogger, IDisposable
    {
        private readonly string tableName;

        private readonly SqlConnection connection;

        public bool ListenLogMessage { get; set; }
        public bool ListenLogReturn { get; set; }
        public bool ListenLogSQL { get; set; }
        public bool ListenLogEntry { get; set; }
        public bool ListenLogException { get; set; }

        public SqlLogger(string config)
        {
            var configParts = config.Split('|');

            tableName = configParts[1];
            connection = new SqlConnection(ConfigurationManager.ConnectionStrings[configParts[0]].ConnectionString);
        }

        public void Log(LogData logData)
        {
            try
            {
                if (!logData.ShouldLog(ListenLogMessage, ListenLogReturn, ListenLogSQL, ListenLogEntry, ListenLogException))
                    return;

                //var logType = string.Empty;
                //if(logData is SQLLogData)
                //{
                //    logType = ""

                //}

                int line = 0;
                int.TryParse(logData.Line, out line);


                var parameters = new List<SqlParameter>{
				    new SqlParameter("@Type",SqlDbType.NVarChar,60){Value = logData.GetType().Name}, 
				    new SqlParameter("@Thread",SqlDbType.Int){Value = logData.ContextThread.GetHashCode()}, 
				    new SqlParameter("@Date",SqlDbType.DateTime){Value = logData.CreationDate}, 
				    new SqlParameter("@Line",SqlDbType.Int){Value = line}, 
				    new SqlParameter("@File",SqlDbType.NVarChar,150){Value = logData.FileName}, 
				    new SqlParameter("@Method",SqlDbType.NVarChar,150){Value = string.Format("{0}({1})",logData.Method,logData.ParametersDeclaration)}, 
				    new SqlParameter("@Message",SqlDbType.NVarChar,150){Value = logData.Message}, 
				    new SqlParameter("@Information",SqlDbType.Text){Value = logData.Information}
                };


                string statement = "INSERT INTO [" + tableName + "] ([Tipo], [Thread], [Data], [Linha], [Arquivo], [Metodo], [Mensagem], [Informacao]) VALUES (@Type, @Thread, @Date, @Line, @File, @Method, @Message, @Information)";

                SqlHelper.ExecuteNonQuery(connection, CommandType.Text, statement, parameters.ToArray());

            }
            catch 
            {
                //silents errors
                
            }


        }

        public void Dispose()
        {
            if(connection.State==ConnectionState.Open)
                connection.Close();

            connection.Dispose();
        }
    }
}